package com.wdc.binarysearch;



public class BinarySearch {


    /**
     * 二分查找
     * @param a 待查找的升序数组
     * @param target 待查找的目标值
     * @return 找到返回索引、没找到返回 -1
     */
    public static int binarySearchBasic(int[] a,int target){
        int left = 0;
        int right = a.length - 1;

        while(left <= right){
            int m = (left+right)/2;

            if(a[m] < target){
                left = m +1;
            }else if (a[m] > target) {
                right = m - 1;
            }else {
                return m;
            }
        }

        return -1;
    }

    /**
     * 线性查找
     * @param a 待查找的数组
     * @param target 待查找的目标值
     * @return 找到返回索引、没找到返回 -1
     */

    public static int linearSearch(int[] a,int target){
        for (int i = 0; i < a.length; i++) {
            if (a[i] == target){
                return i;
            }
        }
        return -1;
    }



}
